//
//  M1CertifyBaseVC.m
//  NewMarryU
//
//  Created by linl on 2018/7/19.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1CertifyBaseVC.h"

#import "M1CertifyPhotoCell.h"

#import "KSPhotoBrowser.h"

static NSString * const CertifyPhotoCell = @"M1CertifyPhotoCell";

@interface M1CertifyBaseVC () <M1CertifyPhotoCellDelegate>

@end

@implementation M1CertifyBaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.m1_photos = [[NSMutableArray alloc] init];
    
    self.m1_maxPhoto = 3;
    
    [self.m1_collectionView registerClass:[M1CertifyPhotoCell class] forCellWithReuseIdentifier:CertifyPhotoCell];
    
    UIBarButtonItem *m1_right = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(m1_doSubmit:)];
    self.navigationItem.rightBarButtonItem = m1_right;
    self.navigationItem.rightBarButtonItem.tintColor = m1_color(0x333333);
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - lazy load
- (UICollectionView *)m1_collectionView
{
    if (!_m1_collectionView) {
        _m1_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, STATUS_HEIGHT + 44, SCREENWIDTH, SCREENHEIGHT - STATUS_HEIGHT - 44) collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
        _m1_collectionView.backgroundColor = [UIColor whiteColor];
        _m1_collectionView.dataSource = self;
        _m1_collectionView.delegate = self;
        [_m1_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
        [self.view addSubview:_m1_collectionView];
    }
    return _m1_collectionView;
}

#pragma mark - private
- (UIImage*)m1_imageFromSdcache:(NSString *)url{
    
    NSData*imageData =nil;
    
    NSString*cacheImageKey = [[SDWebImageManager sharedManager]cacheKeyForURL:[NSURL URLWithString:url]];
    
    if(cacheImageKey.length) {
        
        NSString*cacheImagePath = [[SDImageCache sharedImageCache]defaultCachePathForKey:cacheImageKey];
        
        if(cacheImagePath.length) {
            
            imageData = [NSData dataWithContentsOfFile:cacheImagePath];
            
        }
        
    }
    
    UIImage*image = [UIImage imageWithData:imageData];
    
    return image;
    
}

#pragma mark - overwrite
- (void)m1_enableRightBtn
{
    
}

- (void)m1_requestCertify:(NSString *)imgJson
{
    
}

#pragma mark - UI
- (void)m1_doSubmit:(id)sender
{
    //区分image和url形式的图片
    NSMutableArray *imgs = [[NSMutableArray alloc] init];
    NSMutableArray *imgUrls = [[NSMutableArray alloc] init];
    for(int i = 0 ; i < self.m1_photos.count ; i++) {
        id data = self.m1_photos[i];
        if ([data isKindOfClass:[UIImage class]]) {
            [imgs addObject:data];
        }
        if (i > 0 && [data isKindOfClass:[NSString class]]) {
            [imgUrls addObject:data];
        }
    }
    if (imgs.count) {
        [[M1FileUpload manager] m1_uploadImages:imgs progress:^(CGFloat progress) {
            
        } completion:^(NSArray<NSString *> * _Nullable urls, NSArray<NSDictionary *> * _Nullable pictures, NSError * _Nullable error) {
            NSMutableArray<NSDictionary *> *array = [pictures mutableCopy];
            //加入url形式的图片
            if (imgUrls.count) {
                for (NSString *str in imgUrls) {
                    CGSize size = [self m1_imageFromSdcache:str].size;
                    NSDictionary *dic = @{@"pic":str,@"size":[NSString stringWithFormat:@"%dx%d", (int)size.width, (int)size.height]};
                    [array addObject:dic];
                }
            }
            [self m1_requestCertify:[array mj_JSONString]];
        }];
    } else {
        NSMutableArray<NSDictionary *> *array = [[NSMutableArray alloc] init];
        for (NSString *str in imgUrls) {
            CGSize size = [self m1_imageFromSdcache:str].size;
            NSDictionary *dic = @{@"pic":str,@"size":[NSString stringWithFormat:@"%dx%d", (int)size.width, (int)size.height]};
            [array addObject:dic];
        }
        [self m1_requestCertify:[array mj_JSONString]];
    }
    
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //重用cell
    M1CertifyPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CertifyPhotoCell forIndexPath:indexPath];
    
    cell.m1_selectIndex = indexPath;
    
    cell.m1_maxPhoto = self.m1_maxPhoto;
    
    cell.delegate = self;
    
    [cell m1_refreshCell:self.m1_photos des:self.m1_desDic];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(self.view.frame.size.width, 300);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (collectionView.frame.size.width - 16.0 - 30.0 - 30.0) / 2;
    
    CGFloat scale = 112.0 / 151.0;
    
    return CGSizeMake(width, width * scale + 30);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 30, 0, 30);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 16;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 16;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == [self.m1_photos count])
    {
        if ([self.m1_photos count] <= self.m1_maxPhoto)
        {
            M1SheetView *m1_sheet = [[M1SheetView alloc]initWithTitles:@[@"拍照",@"从相册选择"]];
            
            m1_sheet.click = ^(NSInteger index) {
                
                [[M1ImagePick manager] m1_pickImages:^(NSArray *photos) {
                    
                    [self.m1_photos addObjectsFromArray:photos];

                    [self viewDidLayoutSubviews];
                    
                    [self m1_enableRightBtn];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [self.m1_collectionView reloadData];
                        
                    });
                } type:index maxCount:(self.m1_maxPhoto - self.m1_photos.count + 1) vc:self];
            };
            [m1_sheet m1_show];
        }
    }
    else
    {
        NSMutableArray *items = @[].mutableCopy;
        for (int i = 0; i < _m1_photos.count; i++) {
            M1CertifyPhotoCell *cell = (M1CertifyPhotoCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            id data = _m1_photos[i];
            if (i == 0) {
                KSPhotoItem *item = [KSPhotoItem itemWithSourceView:cell.m1_imgHead image:[UIImage imageNamed:data]];
                [items addObject:item];
            } else {
                if ([data isKindOfClass:[UIImage class]]) {
                    KSPhotoItem *item = [KSPhotoItem itemWithSourceView:cell.m1_imgHead image:data];
                    [items addObject:item];
                } else if ([data isKindOfClass:[NSString class]]) {
                    KSPhotoItem *item = [KSPhotoItem itemWithSourceView:cell.m1_imgHead imageUrl:[NSURL URLWithString:data]];
                    [items addObject:item];
                }
            }
        }
        KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:items selectedIndex:indexPath.item];
//        browser.delegate = self;
        browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleRotation;
        browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlur;
        browser.loadingStyle = KSPhotoBrowserImageLoadingStyleIndeterminate;
//        browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDel;
        browser.bounces = YES;
        [browser showFromViewController:self];
    }
}

#pragma mark - M1CertifyPhotoCellDelegate
- (void)certifyPhotoCell:(M1CertifyPhotoCell *)cell didClickDeleteButton:(UIButton *)sender
{
    NSIndexPath *indexPath = [self.m1_collectionView indexPathForCell:cell];
    
    [self.m1_photos removeObjectAtIndex:indexPath.item];
    
    [self viewDidLayoutSubviews];
    
    [self.m1_collectionView reloadData];
    
    [self m1_enableRightBtn];
}

@end
